package com.test.auth_db_auto.support.oauth2;

import com.test.auth_db_auto.response.HttpResponse;
import com.test.auth_db_auto.utils.HttpUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理Token相关的异常
 * @ Author: .Mr
 * @ ClassName BootOAuth2AuthExceptionEntryPoint
 * @ Description TODO
 * @ date 2021/12/17 14:31
 * @ Version 1.0
 */
@Component
public class BootOAuth2AuthExceptionEntryPoint extends OAuth2AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        String message=e.getMessage();
        if(message.contains("Invalid access token:")){
            String [] info=message.split(":");
            message="access_token无效:"+info[1];
        }
        HttpUtils.writer(HttpResponse.baseResponse(HttpStatus.UNAUTHORIZED.value(),
                message),response);
                super.commence(request, response, e);
    }
}
